package com.hqyj.javaSpringCloudAccount.dao;

import com.hqyj.entity.account.User;
import com.hqyj.entity.common.SearchBean;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserDao {

    @Select("select * from account_user where id = #{id}")
    @Results(id = "userResult", value = {
            @Result(column = "id",property = "id"),
            @Result(column = "id", property = "roles",
            javaType = List.class,
            many = @Many(select = "com.hqyj.javaSpringCloudAccount.dao.RoleDao.getRolesByUserId"))
    })
    User getUserById(int id);

    @Select("select * from account_user where user_name = #{userName} and password = #{password}")
    User getUserByUserNameAndUserPassword(@Param("userName") String userName,
                                          @Param("password") String password);

    @Insert("insert into account_user (create_date, user_name, email, password, user_image) " +
            "values(#{createDate}, #{userName}, #{email}, #{password}, #{userImage})")
    @Options(useGeneratedKeys=true, keyColumn = "id", keyProperty="id")
    void insertUser(User user);

    @Select("<script>"
            + "select * from account_user "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (email like '%${keyword}%' or "
            + " user_name like '%${keyword}%') "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<User> getUsersBySearchVo(SearchBean searchBean);

    @Update("update account_user set user_name = #{userName}, email = #{email}, password = #{password}, user_image = #{userImage} " +
            "where id = #{id}")
    void updateUser(User user);

    @Delete("delete from account_user where id = #{id}")
    void deleteUserById(int id);

    @Select("select * from account_user where user_name = #{userName} or email = #{email}")
    List<User> getUserByUserNameOrEmail(@Param("userName") String userName, @Param("email") String email);

    @Select("select * from account_user where user_name = #{userName}")
    User getUserByUserName(String userName);
}
